package com.dgut.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dgut.entity.*;
import com.dgut.mapper.DeliverynotesMapper;
import com.dgut.mapper.ProductsMapper;
import com.dgut.mapper.SalesOrdersMapper;
import com.dgut.service.DeliverynotesService;
import com.dgut.service.PurchaseOrderService;
import com.dgut.service.SalescontractsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author zhouxiaojun0512
 * @description 针对表【deliverynotes】的数据库操作Service实现
 * @createDate 2024-12-01 10:24:10
 */
@Service
@Slf4j
public class DeliverynotesServiceImpl extends ServiceImpl<DeliverynotesMapper, Deliverynotes>
        implements DeliverynotesService {
    @Autowired
    private SalescontractsService salescontractsService;
    @Autowired
    private SalesOrdersMapper salesOrdersMapper;
    @Autowired
    private ProductsMapper productsMapper;
    @Autowired
    private PurchaseOrderService purchaseOrderService;

    /**
     * 生成发货单
     *
     * @param deliverynotes
     */
    @Override
    @Transactional
    public void add(Deliverynotes deliverynotes) {
        //先修改对应订单和合同数据

        // 先找到对应订单
        SaleOrders orders = salesOrdersMapper.selectById(deliverynotes.getOrderId());
        // 修改订单已支付数量
        orders.setPayedCount(orders.getPayedCount() + deliverynotes.getQuantityShipped());

        // 修改订单状态
        if (orders.getPayedCount() != orders.getQuantity()) {
            if (orders.getPayStatus() == SaleOrders.UNPAY) {//只有未支付状态才修改
                orders.setPayStatus(SaleOrders.PARTIAL_PAYED);//修改订单状态 为部分支付状态
            }
        } else {
            orders.setPayStatus(SaleOrders.PAYED);//修改订单状态 为已全部支付状态
        }
        // 修改数据库订单数据
        salesOrdersMapper.updateById(orders);

        //修改合同数据
        Salescontracts salescontracts = salescontractsService.getById(orders.getContractId());
        if (salescontracts.getContractStatus() == Salescontracts.UNACT) {//未生效合同才生效
            salescontracts.setContractStatus(Salescontracts.ACTING);
            salescontractsService.updateById(salescontracts);
        }

        deliverynotes.setCreateTime(LocalDateTime.now());//设置发货单创建时间

        //最后提交发货单
        this.save(deliverynotes);
    }

    /**
     * 修改发货单(发货)
     *
     * @param deliverynotes
     * @return
     */
    @Override
    @Transactional
    public String update(Deliverynotes deliverynotes) {
        deliverynotes.setStatus(1);//修改发货单状态为已发货

        //修改商品数据
        Long productId = deliverynotes.getProductId();
        Products products = productsMapper.selectById(productId);
        //检验仓库库存量
        Integer handCount = products.getHandCount();
        if (handCount >= deliverynotes.getQuantityShipped()) {
            products.setHandCount(handCount - deliverynotes.getQuantityShipped());

            productsMapper.updateById(products);//先更新商品库存
            this.updateById(deliverynotes);//再更新发货单状态

            //如果发货后库存量低于目标库存量，则生成进货单
            if (products.getHandCount() < products.getTargetCount()) {
                int count = products.getTargetCount() * 2 - handCount;
                PurchaseOrder purchaseOrder = PurchaseOrder.builder()
                        .productId(productId)
                        .quantityOrdered(count)
                        .build();
                purchaseOrderService.save(purchaseOrder);
            }
        } else {
            log.info("库存不足");
            //生成进货单 （未完成）
            int count = deliverynotes.getQuantityShipped() - handCount;
            count = (int) (count + Math.ceil(products.getTargetCount() * 2));
            PurchaseOrder purchaseOrder = PurchaseOrder.builder()
                    .productId(productId)
                    .quantityOrdered(count)
                    .build();
            purchaseOrderService.save(purchaseOrder);
            return "failure";
        }

        //如果一个合同所涉及的所有商品均已发货完毕，则该合同履行完毕。

        // 根据发货单的订单id查询订单并修改状态
        SaleOrders orders = salesOrdersMapper.selectById(deliverynotes.getOrderId());
        if (orders.getPayedCount() != orders.getQuantity()) {
            if (orders.getSendStatus() == SaleOrders.UNSEND) {
                orders.setSendStatus(SaleOrders.PARTAL_SENDED);//修改订单状态 为部分发货状态
                salesOrdersMapper.updateById(orders);
            }
        } else {
            orders.setSendStatus(SaleOrders.ALLSENDED);//修改订单状态 为全部发货状态
            salesOrdersMapper.updateById(orders);

            // 获取该订单对应的合同
            Long contractId = orders.getContractId();
            boolean flag = checkAllOrdersIsFinished(contractId);
        }
        return "success";
    }

    /**
     * 检查某合同下是否所有订单都发货完毕
     *
     * @param contractId
     * @return
     */
    //如果一个合同所涉及的所有商品均已发货完毕，则该合同履行完毕。
    public boolean checkAllOrdersIsFinished(Long contractId) {
        Salescontracts salescontract = salescontractsService.getById(contractId);
        // 查询该合同下所有订单
        QueryWrapper<SaleOrders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("contract_id", contractId);
        List<SaleOrders> saleOrders = salesOrdersMapper.selectList(queryWrapper);

        for (SaleOrders saleOrder : saleOrders) {
            // 判断订单下所有发货单是否全部发货完毕
            if (saleOrder.getSendStatus() != SaleOrders.ALLSENDED) {
                return false;
            }
        }

        // 所有订单都发货完毕，则该合同完成
        salescontract.setContractStatus(Salescontracts.FINISH);
        salescontractsService.updateById(salescontract);
        return true;
    }
}


